package com.wc.alorithm_luogu.P2234;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;

/**
 * @Author congge
 * @Date 2023/5/21 12:56
 * @description https://www.luogu.com.cn/problem/P2234
 * [HNOI2002]营业额统计  (插入排序)
 */
public class Main {
    public static void main(String[] args) {
        Input sc = new Input();
        int n = sc.next();
        int[] array = new int[n];

        int ans = 0;
        array[0] = sc.next();
        ans += array[0];
        for (int i = 1; i < n; i++) {
            array[i] = sc.next();
        }

        for (int i = 1; i < n; i++) {
            int tmp = array[i];
            int j = i - 1;
            while (j >= 0) {
                if (array[j] > tmp) {
                    array[j + 1] = array[j];
                } else {
                    break;
                }
                j--;
            }
            array[j + 1] = tmp;

            if (j + 1 == i) {
                ans += Math.abs(array[j + 1] - array[j]);
            } else if (j + 1 == 0) {
                ans += Math.abs(array[j + 1] - array[j + 2]);
            } else {
                ans += Math.min(Math.abs(array[j + 1] - array[j]), Math.abs(array[j + 1] - array[j + 2]));
            }
        }
//        System.out.println(Arrays.toString(array));
        System.out.println(ans);
    }

    static class Input {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

        public int next() {
            try {
                in.nextToken();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return (int) in.nval;
        }
    }
}
